<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="deviceCode">
        <el-input v-model="queryParams.deviceCode" placeholder="请输入设备编号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型">
          <el-option v-for="dict in deviceTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="parseInt(dict.dictValue)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="deviceStatus">
        <el-select v-model="queryParams.deviceStatus" placeholder="请选择设备状态">
          <el-option v-for="dict in deviceStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物联卡号" prop="iotCardNo">
        <el-input v-model="queryParams.iotCardNo" placeholder="请输入物联卡号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['iot:device:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['iot:device:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:device:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading" @click="handleExport" v-hasPermi="['iot:device:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编号" align="center" prop="deviceCode" width="100" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="设备类型" align="center" prop="deviceType" :formatter="deviceTypeFormat" />
      <el-table-column label="设备状态" align="center" prop="deviceStatus" :formatter="deviceStatusFormat" />
      <el-table-column label="物联卡号" align="center" prop="iotCardNo" />
      <el-table-column label="物联卡类型" align="center" prop="iotCardType" width="100" :formatter="deviceStatusFormat" />
      <el-table-column label="最后传值时间" align="center" prop="lastTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="经度" align="center" prop="lng" width="100" />
      <el-table-column label="纬度" align="center" prop="lat" width="100" />
      <el-table-column label="地址" align="center" prop="address" width="180" />
      <el-table-column label="备注" align="center" prop="remark" width="180" />
      <el-table-column label="井顶值" align="center" prop="jdz" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:device:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:device:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="form_default">
        <div class="form_item_head">基本信息</div>
        <el-form-item label="设备编号" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型">
            <el-option v-for="dict in deviceTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="parseInt(dict.dictValue)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-select v-model="form.deviceStatus" placeholder="请选择设备状态">
            <el-option v-for="dict in deviceStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物联卡号" prop="iotCardNo">
          <el-input v-model="form.iotCardNo" placeholder="请输入物联卡号" />
        </el-form-item>
        <el-form-item label="物联卡类型" prop="iotCardType">
          <el-select v-model="form.iotCardType" placeholder="请选择物联卡类型">
            <el-option v-for="dict in iotCardTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="parseInt(dict.dictValue)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="form.lng" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" />
        </el-form-item>
        <!-- <el-form-item label="最后传值时间" prop="lastTime">
          <el-date-picker clearable size="small"
            v-model="form.lastTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择最后传值时间">
          </el-date-picker>
        </el-form-item> -->

        <el-form-item label="井顶值" prop="jdz">
          <el-input v-model="form.jdz" placeholder="请输入井顶值" />
        </el-form-item>
        <el-form-item label="地址" prop="address" class="width100">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="设备报警参数" class="width100">
          <el-button type="primary" plain @click="addItem">添加报警参数</el-button>
          <div v-if="form.configList && form.configList.length != 0">
            <div class="device_baojing_cs" v-for="(item, index) in form.configList" :key="index">
              <el-select v-model="item.monitoringType" placeholder="请选择设备参数">
                <el-option v-for="dict in deviceCsOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="parseInt(dict.dictValue)"></el-option>
              </el-select>
              <el-form-item style="width: auto" label="最小值" :prop="'configList.' + index + '.yjz'" :rules="{ required: true, message: '最小值不能为空', trigger: 'blur'  }">
                <el-input style="width: 200px" v-model="item.yjz"></el-input>
              </el-form-item>
              <el-form-item style="width: auto" label="最大值" :prop="'configList.' + index + '.bjz'" :rules="{ required: true, message: '最大值不能为空', trigger: 'blur'  }">
                <el-input style="width: 200px" v-model="item.bjz"></el-input>
              </el-form-item>
              <i class="el-icon-delete" style="font-size:20px; cursor: pointer; margin-left:20px;" @click="deleteItem(index)"></i>
              <i class="el-icon-plus" style="font-size:20px; cursor: pointer; margin-left:20px;" @click="addItem" v-show="form.configList.length-1 == index"></i>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="备注" prop="remark" class="width100">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice,
  exportDevice,
  checkBaseDeviceCodeUnique,
} from "@/api/iot/device";

export default {
  name: "Device",
  data() {
    return {
      // 设备参数
      deviceCs: null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 设备类型字典
      deviceTypeOptions: [],
      // 设备状态字典
      deviceStatusOptions: [],
      // 物联卡类型字典
      iotCardTypeOptions: [],
      // 设备参数字典
      deviceCsOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prjNo: null,
        prjName: null,
        deviceCode: null,
        deviceName: null,
        deviceType: null,
        deviceStatus: null,
        deviceValue: null,
        lng: null,
        lat: null,
        lastTime: null,
        address: null,
        iotCardNo: null,
        iotCardType: null,
        isSure: null,
        jdz: null,
        configList: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceCode: [
          { required: true, message: "设备编号不能为空", trigger: "blur" },
        ],
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" },
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "change" },
        ],
        deviceStatus: [
          { required: true, message: "设备状态不能为空", trigger: "blur" },
        ],
        iotCardNo: [
          { required: true, message: "物联卡号不能为空", trigger: "blur" },
        ],
        lng: [{ required: true, message: "经度不能为空", trigger: "blur" }],
        lat: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("device_type").then((response) => {
      this.deviceTypeOptions = response.data;
    });
    this.getDicts("device_status").then((response) => {
      this.deviceStatusOptions = response.data;
    });
    this.getDicts("iot_card_type").then((response) => {
      this.iotCardTypeOptions = response.data;
    });
    this.getDicts("device_alarm_type").then((response) => {
      this.deviceCsOptions = response.data;
    });
  },
  methods: {
    addItem() {
      this.form.configList.push({
        monitoringType: null,
        yjz: null,
        bjz: null,
      });
    },
    deleteItem(i) {
      this.form.configList.splice(i, 1);
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then((response) => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 设备类型字典翻译
    deviceTypeFormat(row, column) {
      return this.selectDictLabel(this.deviceTypeOptions, row.deviceType);
    },
    // 设备状态字典翻译
    deviceStatusFormat(row, column) {
      return this.selectDictLabel(this.deviceStatusOptions, row.deviceStatus);
    },
    // 物联卡类型字典翻译
    iotCardTypeFormat(row, column) {
      return this.selectDictLabel(this.iotCardTypeOptions, row.iotCardType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        prjNo: null,
        prjName: null,
        deviceCode: null,
        deviceName: null,
        deviceType: null,
        deviceStatus: null,
        deviceValue: null,
        lng: null,
        lat: null,
        lastTime: null,
        address: null,
        iotCardNo: null,
        iotCardType: null,
        isSure: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        jdz: null,
        configList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.deviceId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids;
      getDevice(deviceId).then((response) => {
        this.form = response.data;
        if (response.data.configList == null) {
          this.form.configList = [];
        }
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.deviceId != null) {
            this.checkCode(this.form.deviceCode, this.form.deviceId).then(
              (res) => {
                if (res) {
                  updateDevice(this.form).then((response) => {
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  });
                } else {
                  this.msgError("设备编号必须唯一");
                }
              }
            );
          } else {
            this.checkCode(this.form.deviceCode).then((res) => {
              if (res) {
                if (this.isRepeat(this.form.configList)) {
                  this.msgError("设备报警参数不能重复");
                } else {
                  addDevice(this.form).then((response) => {
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  });
                }
              } else {
                this.msgError("设备编号必须唯一");
              }
            });
          }
        }
      });
    },
    /** 判断数组是否有重复 */
    isRepeat(arr) {
      var hash = {};
      for (var i in arr) {
        let item = arr[i].monitoringType;
        console.log(item);
        if (hash[item]) return true;
        hash[item] = true;
      }
      return false;
    },
    /** 检测编号是否唯一 */
    async checkCode(deviceCode, deviceId) {
      let params = {};
      if (deviceId) {
        params = { deviceCode, deviceId };
      } else {
        params = { deviceCode };
      }
      let flag = false;
      let res = await checkBaseDeviceCodeUnique(params);
      if (res == 0) {
        flag = true;
      } else {
        flag = false;
      }
      return flag;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$confirm(
        '是否确认删除设备编号为"' + deviceIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delDevice(deviceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有设备数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportDevice(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.device_baojing_cs {
  display: flex;
  padding: 12px 0;
}
</style>